package com.yvon.gprc.server.service;

import com.yvon.grpc.api.CalculateProto;
import com.yvon.grpc.api.CalculateServiceGrpc;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;

/**
 * @author : wangyufeng
 * @since : 2021-10-19
 */
@GrpcService
@Slf4j
public class CalculateService extends CalculateServiceGrpc.CalculateServiceImplBase {

    @Override
    public StreamObserver<CalculateProto.Value> getResult(StreamObserver<CalculateProto.Result> responseObserver) {
        return new StreamObserver<CalculateProto.Value>() {
            private int sum = 0;
            private int cnt = 0;
            private double avg;

            @Override
            public void onNext(CalculateProto.Value value) {
                log.info("服务端：接收到信息为{}", value.getValue());
                sum += value.getValue();
                cnt ++;
                avg = 1.0*sum/cnt;

                // 返回当前统计结果
                CalculateProto.Result result = CalculateProto.Result.newBuilder().setSum(sum).setCnt(cnt).setAvg(avg).build();
                log.info("服务端：返回的消息为：{}", result);
                responseObserver.onNext(result);

            }

            @Override
            public void onError(Throwable throwable) {
                log.warn("服务端：调用出错:{}",throwable.getMessage());
            }

            @Override
            public void onCompleted() {
                responseObserver.onCompleted();
            }
        };
    }
}
